<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

if ( ! function_exists('remove_invisible_characters'))
{
    function remove_invisible_characters($str, $url_encoded = TRUE)
    {
        $non_displayables = array();

        // every control character except newline (dec 10)
        // carriage return (dec 13), and horizontal tab (dec 09)

        if ($url_encoded)
        {
            $non_displayables[] = '/%0[0-8bcef]/';	// url encoded 00-08, 11, 12, 14, 15
            $non_displayables[] = '/%1[0-9a-f]/';	// url encoded 16-31
        }

        $non_displayables[] = '/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]+/S';	// 00-08, 11, 12, 14-31, 127

        do
        {
            $str = preg_replace($non_displayables, '', $str, -1, $count);
        }
        while ($count);

        return $str;
    }
}




class static_page
{
    var $config = Array();
    var $uri;
    var $uri_string;

    function _set_uri_string($str)
    {
        // Filter out control characters
        $str = remove_invisible_characters($str, FALSE);

        // If the URI contains only a slash we'll kill it
        $this->uri_string = ($str == '/') ? '' : $str;
    }

    private function _parse_cli_args()
    {
        $args = array_slice($_SERVER['argv'], 1);

        return $args ? '/' . implode('/', $args) : '';
    }



    /**
     * Detects the URI
     *
     * This function will detect the URI automatically and fix the query string
     * if necessary.
     *
     * @access	private
     * @return	string
     */
    private function _detect_uri()
    {
        if ( ! isset($_SERVER['REQUEST_URI']) OR ! isset($_SERVER['SCRIPT_NAME']))
        {
            return '';
        }

        $uri = $_SERVER['REQUEST_URI'];
        if (strpos($uri, $_SERVER['SCRIPT_NAME']) === 0)
        {
            $uri = substr($uri, strlen($_SERVER['SCRIPT_NAME']));
        }
        elseif (strpos($uri, dirname($_SERVER['SCRIPT_NAME'])) === 0)
        {
            $uri = substr($uri, strlen(dirname($_SERVER['SCRIPT_NAME'])));
        }

        // This section ensures that even on servers that require the URI to be in the query string (Nginx) a correct
        // URI is found, and also fixes the QUERY_STRING server var and $_GET array.
        if (strncmp($uri, '?/', 2) === 0)
        {
            $uri = substr($uri, 2);
        }
        $parts = preg_split('#\?#i', $uri, 2);
        $uri = $parts[0];
        if (isset($parts[1]))
        {
            $_SERVER['QUERY_STRING'] = $parts[1];
            parse_str($_SERVER['QUERY_STRING'], $_GET);
        }
        else
        {
            $_SERVER['QUERY_STRING'] = '';
            $_GET = array();
        }

        if ($uri == '/' || empty($uri))
        {
            return '/';
        }

        $uri = parse_url($uri, PHP_URL_PATH);

        // Do some final cleaning of the URI and return it
        return str_replace(array('//', '../'), '/', trim($uri, '/'));
    }

    function _fetch_uri_string()
    {
        if (strtoupper($this->config['uri_protocol']) == 'AUTO')
        {
            // Is the request coming from the command line?
            if (php_sapi_name() == 'cli' or defined('STDIN'))
            {
                $this->_set_uri_string($this->_parse_cli_args());
                return;
            }

            // Let's try the REQUEST_URI first, this will work in most situations
            if ($uri = $this->_detect_uri())
            {
                $this->_set_uri_string($uri);
                return;
            }

            // Is there a PATH_INFO variable?
            // Note: some servers seem to have trouble with getenv() so we'll test it two ways
            $path = (isset($_SERVER['PATH_INFO'])) ? $_SERVER['PATH_INFO'] : @getenv('PATH_INFO');
            if (trim($path, '/') != '' && $path != "/".SELF)
            {
                $this->_set_uri_string($path);
                return;
            }

            // No PATH_INFO?... What about QUERY_STRING?
            $path =  (isset($_SERVER['QUERY_STRING'])) ? $_SERVER['QUERY_STRING'] : @getenv('QUERY_STRING');
            if (trim($path, '/') != '')
            {
                $this->_set_uri_string($path);
                return;
            }

            // As a last ditch effort lets try using the $_GET array
            if (is_array($_GET) && count($_GET) == 1 && trim(key($_GET), '/') != '')
            {
                $this->_set_uri_string(key($_GET));
                return;
            }

            // We've exhausted all our options...
            $this->uri_string = '';
            return;
        }

        $uri = strtoupper($this->config['uri_protocol']);

        if ($uri == 'REQUEST_URI')
        {
            $this->_set_uri_string($this->_detect_uri());
            return;
        }
        elseif ($uri == 'CLI')
        {
            $this->_set_uri_string($this->_parse_cli_args());
            return;
        }

        $path = (isset($_SERVER[$uri])) ? $_SERVER[$uri] : @getenv($uri);
        $this->_set_uri_string($path);
    }



    // --------------------------------------------------------------------

    /**
     * Filter segments for malicious characters
     *
     * @access	private
     * @param	string
     * @return	string
     */
    function _filter_uri($str)
    {
        if ($str != '' && $this->config['permitted_uri_chars'] != '' && $this->config['enable_query_strings'] == FALSE)
        {
            // preg_quote() in PHP 5.3 escapes -, so the str_replace() and addition of - to preg_quote() is to maintain backwards
            // compatibility as many are unaware of how characters in the permitted_uri_chars will be parsed as a regex pattern
            if ( ! preg_match("|^[".str_replace(array('\\-', '\-'), '-', preg_quote($this->config['permitted_uri_chars'], '-'))."]+$|i", $str))
            {
                show_error('The URI you submitted has disallowed characters.', 400);
            }
        }

        // Convert programatic characters to entities
        $bad	= array('$',		'(',		')',		'%28',		'%29');
        $good	= array('&#36;',	'&#40;',	'&#41;',	'&#40;',	'&#41;');

        return str_replace($bad, $good, $str);
    }



    function execute()
    {
        if(CONTROL_FOLDER == "admin")
        {
            return;
        }
        // $this->config =& load_class('Config', 'core');

        $config = Array();
        $config_file = FCPATH."application/config/config.php";
        if(file_exists($config_file)){
            // exit("bb");
            require($config_file);
        }
        $this->config = $config;

        // print_r($config);exit;
        $segments = array();
        $class = "";
        $method = "";
        if ($this->config['enable_query_strings'] === TRUE AND isset($_GET[$this->config['controller_trigger']]))
        {
            if (isset($_GET[$this->config['controller_trigger']]))
            {
                $class = trim($this->_filter_uri($_GET[$this->config['controller_trigger']]));
                $class = str_replace(array('/', '.'), '', $class);
            }

            if (isset($_GET[$this->config['function_trigger']]))
            {
                $method = trim($this->_filter_uri($_GET[$this->config['function_trigger']]));
                if ($method == $class)
                {
                    $segments[] =  'index';
                }

                $segments[] =  $method;
            }

            $this->uri_string = $class."/$method";
        }
        else
        {
            // print_r($segments);exit;
            $this->_fetch_uri_string();

            // Is there a URI string? If not, the default controller specified in the "routes" file will be shown.
            if ($this->uri_string == '')
            {
                // return $this->_set_default_controller();
                if (defined('ENVIRONMENT') AND is_file(APPPATH.'config/'.ENVIRONMENT.'/routes.php'))
                {
                    include(APPPATH.'config/'.ENVIRONMENT.'/routes.php');
                }
                elseif (is_file(APPPATH.'config/routes.php'))
                {
                    include(APPPATH.'config/routes.php');
                }

                $routes = ( ! isset($route) OR ! is_array($route)) ? array() : $route;
                unset($route);

                if(count($segments)>0){

                }

                // print_r()
                $default_controller = ( ! isset($routes['default_controller']) OR $routes['default_controller'] == '') ? FALSE : strtolower($routes['default_controller']);
                $default_controller = str_replace(CONTROL_FOLDER."/","",$default_controller);
                $this->uri_string = $default_controller."/index";
            }

        }

        // echo $this->uri_string;exit;
        $segments = explode("/",$this->uri_string);
        $class = $segments[0];
        $method = $segments[1];

        // echo $class."-".$method;exit;
        if(strtolower($class) == "entry" && strtolower($method) == "index")
        {
            // exit("aa");
            $path  = FCPATH."application/cache/entry-index.html";
            // echo $path;exit;
            if(file_exists($path)){
                // exit("aa");
                // require_once($path);
                $entry_info = unserialize(file_get_contents($path));

                if($entry_info['time'] + $entry_info['ttl'] > time())
                {
                    echo $entry_info['data'];

                    $end_time = microtime();
                    if (defined('ENVIRONMENT') && ENVIRONMENT=='development'){
                        echo "<center>Total:".($end_time- PAGE_START_TIME)."</center>";
                    }
                    exit;
                }
            }

        }


        if(strtolower($class) == "article" && strtolower($method) == "index")
        {
            $class_id = $_GET['class-id'];
            $page = isset($_GET['page'])?$_GET['page']:1;
            $path  = FCPATH."application/cache/article-index-$class_id-$page.html";
            // echo $path;exit;
            if(file_exists($path)){
                // exit("aa");
                // require_once($path);
                $article_index_info = unserialize(file_get_contents($path));

                if($article_index_info['time'] + $article_index_info['ttl'] > time())
                {
                    echo $article_index_info['data'];

                    $end_time = microtime();
                    if (defined('ENVIRONMENT') && ENVIRONMENT=='development'){
                        echo "<center>Total:".($end_time- PAGE_START_TIME)."</center>";
                    }
                    exit;
                }
            }

        }


        if(strtolower($class) == "page" && strtolower($method) == "show")
        {
            $cache_key = "";
            if(isset($segments[2])){
                $cache_key = intval($segments[2]);
            }
            else
            {
                $cache_key = isset($_GET['alias'])?$_GET['alias']:"";
            }
            //  echo $cache_key;exit;
            $path  = FCPATH."application/cache/page-show-".$cache_key.".html";
            if(file_exists($path)){
                // exit("aa");
                // require_once($path);
                $page_info = unserialize(file_get_contents($path));

                if($page_info['time'] + $page_info['ttl'] > time())
                {
                    echo $page_info['data'];

                    $end_time = microtime();
                    if (defined('ENVIRONMENT') && ENVIRONMENT=='development'){
                        echo "<center>Total:".($end_time- PAGE_START_TIME)."</center>";
                    }
                    exit;
                }

                // exit;

            }

        }


        if(strtolower($class) == "article" && strtolower($method) == "show")
        {
            $cache_key = "";
            if(isset($segments[2])){
                $cache_key = intval($segments[2]);
            }
            else
            {
                $cache_key = isset($_GET['alias'])?$_GET['alias']:"";
            }
            $path  = FCPATH."application/cache/article-show-".$cache_key.".html";
            if(file_exists($path)){
                // exit("aa");
                // require_once($path);
                $article_info = unserialize(file_get_contents($path));

                if($article_info['time'] + $article_info['ttl'] > time())
                {
                    echo $article_info['data'];
                }
                // exit;


                $end_time = microtime();
                if (defined('ENVIRONMENT') && ENVIRONMENT=='development'){
                    echo "<center>Total:".($end_time- PAGE_START_TIME)."</center>";
                }
                exit;
            }
        }

        /*
        $end_time = microtime();
        if (defined('ENVIRONMENT') && ENVIRONMENT=='development'){
            echo "<center>Total:".($end_time- PAGE_START_TIME)."</center>";
        }
        exit;*/
    }
}


class pre_controller
{
    function static_page()
    {
        if(CONTROL_FOLDER == "admin")
        {
            return;
        }
        $RTR =& load_class('Router', 'core');
        $class  = $RTR->fetch_class();
        $method = $RTR->fetch_method();

        if(strtolower($class) == "entry" && strtolower($method) == "index")
        {
            $path  = FCPATH."application/cache/entry-index.html";
            // echo $path;exit;
            if(file_exists($path)){
                // exit("aa");
                // require_once($path);
                $entry_info = unserialize(file_get_contents($path));

                if($entry_info['time'] + $entry_info['ttl'] > time())
                {
                    echo $entry_info['data'];

                    $end_time = microtime();
                    if (defined('ENVIRONMENT') && ENVIRONMENT=='development'){
                        echo "<center>Total:".($end_time- PAGE_START_TIME)."</center>";
                    }
                    exit;
                }
            }

        }


        if(strtolower($class) == "article" && strtolower($method) == "index")
        {
            $class_id = $_GET['class-id'];
            $page = isset($_GET['page'])?$_GET['page']:1;
            $path  = FCPATH."application/cache/article-index-$class_id-$page.html";
            // echo $path;exit;
            if(file_exists($path)){
                // exit("aa");
                // require_once($path);
                $article_index_info = unserialize(file_get_contents($path));

                if($article_index_info['time'] + $article_index_info['ttl'] > time())
                {
                    echo $article_index_info['data'];

                    $end_time = microtime();
                    if (defined('ENVIRONMENT') && ENVIRONMENT=='development'){
                        echo "<center>Total:".($end_time- PAGE_START_TIME)."</center>";
                    }
                    exit;
                }
            }

        }


        if(strtolower($class) == "page" && strtolower($method) == "show")
        {
            $cache_key = "";
            if(isset($RTR->uri->segments[3])){
                $cache_key = intval($RTR->uri->segments[3]);
            }
            else
            {
                $cache_key = isset($_GET['alias'])?$_GET['alias']:"";
            }
            $path  = FCPATH."application/cache/page-show-".$cache_key.".html";
            if(file_exists($path)){
                // exit("aa");
                // require_once($path);
                $page_info = unserialize(file_get_contents($path));

                if($page_info['time'] + $page_info['ttl'] > time())
                {
                    echo $page_info['data'];

                    $end_time = microtime();
                    if (defined('ENVIRONMENT') && ENVIRONMENT=='development'){
                        echo "<center>Total:".($end_time- PAGE_START_TIME)."</center>";
                    }
                    exit;
                }

                // exit;

            }

        }


        if(strtolower($class) == "article" && strtolower($method) == "show")
        {
            $cache_key = "";
            if(isset($RTR->uri->segments[3])){
                $cache_key = intval($RTR->uri->segments[3]);
            }
            else
            {
                $cache_key = isset($_GET['alias'])?$_GET['alias']:"";
            }
            $path  = FCPATH."application/cache/article-show-".$cache_key.".html";
            if(file_exists($path)){
                // exit("aa");
                // require_once($path);
                $article_info = unserialize(file_get_contents($path));

                if($article_info['time'] + $article_info['ttl'] > time())
                {
                    echo $article_info['data'];
                }
                // exit;


                $end_time = microtime();
                if (defined('ENVIRONMENT') && ENVIRONMENT=='development'){
                    echo "<center>Total:".($end_time- PAGE_START_TIME)."</center>";
                }
                exit;
            }
        }
        /*
        $id = $cache_key = empty($_GET['id'])?$id:$this->input->get('id');

        if($cache_key==null){
            $cache_key = $this->input->get('alias');
        }
        $this->load->driver('cache', array('adapter' => 'file'));
        if ($page_html = $this->cache->get('page-show-'.$cache_key))
        {
            // echo "aa";
            echo ($page_html);
            return ;
        }*/
        // exit;

    }
}